﻿/*
Copyright (c) 2016 Robert Gaffney
Licensed under the MIT License:

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Kemper_Duplicate_Finder
{
    public partial class Form1 : Form
    {

        /*List<string> sourceFiles;
        List<string> destFiles;
        Dictionary<string, MidiTag> allTags;
        Dictionary<string, List<string>> sourcefilesByTag;
        Dictionary<string, List<string>> destfilesByTag;
        Dictionary<string, List<string>> sourcefilesByAmp;
        Dictionary<string, List<string>> destfilesByAmp;
        Dictionary<string, List<string>> sourcefilesByCab;
        Dictionary<string, List<string>> destfilesByCab;
        Dictionary<string, FileReader> sourceFilesDict;
        Dictionary<string, FileReader> destFilesDict;
        List<string> duplicateTags;*/
        //int duplicateTagCount;
        private MatchEngine engine;
        private Color currentCellColor;

        public Form1()
        {
            InitializeComponent();
            currentCellColor = Color.LightSalmon;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            if (folder.ShowDialog() == DialogResult.OK)
            {
                sourceFolder.Text = folder.SelectedPath;
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            if (folder.ShowDialog() == DialogResult.OK)
            {
                destFolder.Text = folder.SelectedPath;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // check for errors
            if (!Directory.Exists(this.sourceFolder.Text))
            {
                MessageBox.Show("Your Rigs Folder does not point to a valid folder", "Invalid Folder", MessageBoxButtons.OK);
                return;
            }
            if (!Directory.Exists(this.destFolder.Text))
            {
                MessageBox.Show("Compare To Folder does not point to a valid folder", "Invalid Folder", MessageBoxButtons.OK);
                return;
            }

            // find files and duplicate matches        
            this.engine = new MatchEngine();
            engine.run(this.sourceFolder.Text, this.destFolder.Text);

            // populate grid
            this.sourceFileGrid.Rows.Clear();
            this.tagGrid.Rows.Clear();
            this.populateGrid();

            MessageBox.Show("Compared " + engine.sourceFiles.Count + " of Your Rigs against "
                + engine.destFiles.Count + " Compare To rigs."
                + "  Found " + engine.duplicateTags.Count + " duplicate profiles.", "Finished Processing", MessageBoxButtons.OK);

            this.save.Enabled = true;
            this.viewAmpMatches.Enabled = true;
            this.viewCabMatches.Enabled = true;
            this.hideSameAuthor.Enabled = true;
        }

        private void tagGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.tagGrid.CurrentCell.ColumnIndex.Equals(0))
            {
                MessageBox.Show(this.dumpTagsForFile(this.tagGrid.CurrentCell.Value.ToString()), "Tag Data", MessageBoxButtons.OK);
                //textOutputViewer.Text = this.dumpTagsForFile(this.tagGrid.CurrentCell.Value.ToString());
            }
        }

        private void populateGrid()
        {
            /*this.duplicateTags = new List<string>();
            this.tagGrid.Rows.Clear();

            foreach (string sourceFilename in this.sourceFiles)
            {
                FileReader sourceFR;
                if (this.sourceFilesDict.TryGetValue(sourceFilename, out sourceFR))
                {
                    if (this.findProfileMatches("Amp", sourceFR))
                    {
                        this.switchColor();
                    }
                    if (this.findProfileMatches("Cab", sourceFR))
                    {
                        this.switchColor();
                    }                    
                }
            }*/
            this.sourceFileGrid.Rows.Clear();
            this.tagGrid.Rows.Clear();

            uint rowCount = 0;

            string filename = "";
            string type = "";
            string author = "";
            string hash = "";

            foreach (KeyValuePair<string, SourceFile> sourceFile in engine.sourceFiles)
            {
                if (rowCount < 1000)
                {

                    /*if (sourceFile.Value.ampMatchFiles.Count > 0)
                    {
                        filename = sourceFile.Key;
                        type = "Amp";
                        author = sourceFile.Value.fr.getAmpAuthor();
                        hash = sourceFile.Value.fr.ampHash;
                        //this.addGridRow(filename, type, author, hash);
                        this.addSourceFileRow(filename);
                        rowCount++;

                        foreach (KeyValuePair<string, FileReader> match in sourceFile.Value.ampMatchFiles)
                        {
                            filename = match.Key;
                            type = "Amp";
                            author = match.Value.getAmpAuthor();
                            hash = match.Value.ampHash;
                            this.addGridRow(filename, type, author, hash);
                            rowCount++;
                        }
                        this.switchColor();
                    }

                    if (sourceFile.Value.cabMatchFiles.Count > 0)
                    {
                        filename = sourceFile.Key;
                        type = "Cab";
                        author = sourceFile.Value.fr.getCabAuthor();
                        hash = sourceFile.Value.fr.cabHash;
                        //this.addGridRow(filename, type, author, hash);
                        this.addSourceFileRow(filename);
                        rowCount++;

                        foreach (KeyValuePair<string, FileReader> match in sourceFile.Value.cabMatchFiles)
                        {
                            filename = match.Key;
                            type = "Cab";
                            author = match.Value.getCabAuthor();
                            hash = match.Value.cabHash;
                            this.addGridRow(filename, type, author, hash);
                            rowCount++;
                        }
                        this.switchColor();
                    }
                }*/
                    bool display = false;
                    if (this.viewAmpMatches.Checked)
                    {
                        if (sourceFile.Value.ampMatchFiles.Count > 0)
                        {
                            if (this.hideSameAuthor.Checked)
                            {
                                if (sourceFile.Value.differentAmpAuthors)
                                    display = true;
                            }
                            else
                                display = true;
                        }
                    }
                    if (this.viewCabMatches.Checked)
                    {
                        if (sourceFile.Value.cabMatchFiles.Count > 0)
                        {
                            if (this.hideSameAuthor.Checked)
                            {
                                if (sourceFile.Value.differentCabAuthors)
                                    display = true;
                            }
                            else
                                display = true;
                        }
                    }

                    //if (sourceFile.Value.ampMatchFiles.Count > 0 || sourceFile.Value.cabMatchFiles.Count > 0)
                    if (display)
                    {
                        filename = sourceFile.Key;
                        this.addSourceFileRow(filename);
                        this.switchColor();
                        rowCount++;
                    }
                }
                else
                {
                    MessageBox.Show("Over 1000 rows returned - showing partial results.");
                    break;
                }
            }
        }

        private void addSourceFileRow(string filename)
        {
            string filenameNoPath = filename.Substring(filename.LastIndexOf("\\") + 1, filename.Length - filename.LastIndexOf("\\") - 6);
            //DataGridViewCellStyle style = new DataGridViewCellStyle();
            //style.BackColor = this.currentCellColor;
            this.sourceFileGrid.Rows.Add(filename, filenameNoPath);
            //this.sourceFileGrid.Rows[this.sourceFileGrid.RowCount - 1].DefaultCellStyle = style;
        }

        private void addGridRow(string filename, string type, string author, string hash)
        {
            DataGridViewCellStyle style = new DataGridViewCellStyle();
            style.BackColor = this.currentCellColor;
            this.tagGrid.Rows.Add(filename, "", type, author, hash, "");
            this.tagGrid.Rows[this.tagGrid.RowCount - 1].DefaultCellStyle = style;
        }

        private void switchColor()
        {
            if (this.currentCellColor == Color.LightBlue)
            {
                this.currentCellColor = Color.LightCoral; return;
            }
            if (this.currentCellColor == Color.LightCoral)
            {
                this.currentCellColor = Color.LightCyan; return;
            }
            if (this.currentCellColor == Color.LightCyan)
            {
                this.currentCellColor = Color.LightGoldenrodYellow; return;
            }
            if (this.currentCellColor == Color.LightGoldenrodYellow)
            {
                this.currentCellColor = Color.LightGray; return;
            }
            if (this.currentCellColor == Color.LightGray)
            {
                this.currentCellColor = Color.LightGreen; return;
            }
            if (this.currentCellColor == Color.LightGreen)
            {
                this.currentCellColor = Color.LightPink; return;
            }
            if (this.currentCellColor == Color.LightPink)
            {
                this.currentCellColor = Color.LightSalmon; return;
            }
            if (this.currentCellColor == Color.LightSalmon)
            {
                this.currentCellColor = Color.LightSeaGreen; return;
            }
            if (this.currentCellColor == Color.LightSeaGreen)
            {
                this.currentCellColor = Color.LightSkyBlue; return;
            }
            if (this.currentCellColor == Color.LightSkyBlue)
            {
                this.currentCellColor = Color.LightSlateGray; return;
            }
            if (this.currentCellColor == Color.LightSlateGray)
            {
                this.currentCellColor = Color.LightSteelBlue; return;
            }
            if (this.currentCellColor == Color.LightSteelBlue)
            {
                this.currentCellColor = Color.LightYellow; return;
            }
            if (this.currentCellColor == Color.LightYellow)
            {
                this.currentCellColor = Color.LightBlue; return;
            }

            /*i don't think this works - trying to lighten colors*/
            Color c = this.currentCellColor;
            double mlt = 1.25;
            this.currentCellColor = Color.FromArgb((int)(c.A * mlt), (int)(c.R * mlt), (int)(c.G * mlt), (int)(c.B * mlt));
        }

        /*private bool findProfileMatches(string profileType, FileReader sourceFR)
        {
            List<string> fileList;

            string hash = "";
            string destHash = "";
            Dictionary<string, List<string>> filesByHash = new Dictionary<string, List<string>>();
            if (profileType.Equals("Amp"))
            {
                hash = sourceFR.ampHash;
                filesByHash = this.destfilesByAmp;
            }

            if (profileType.Equals("Cab"))
            {
                hash = sourceFR.cabHash;
                filesByHash = this.destfilesByCab;
            }

            if (filesByHash.TryGetValue(hash, out fileList))
            {
                bool nonSameFileMatch = false;
                foreach (string matchFileName in fileList)
                {
                    if (!matchFileName.Equals(sourceFR.path))
                    {
                        nonSameFileMatch = true;
                        break;
                    }
                }

                if (nonSameFileMatch)
                {
                    DataGridViewCellStyle style = new DataGridViewCellStyle();
                    style.BackColor = this.currentCellColor;

                    string author = "";
                    MidiTag tag;
                    if (sourceFR.tagDict.TryGetValue(profileType + " Author", out tag))
                    {
                        author = this.convertHexToString(tag.data);
                    }

                    this.tagGrid.Rows.Add(sourceFR.path, "", profileType, author, hash, "");
                    this.tagGrid.Rows[this.tagGrid.RowCount - 1].DefaultCellStyle = style;

                    if (!this.duplicateTags.Contains(hash))
                    {
                        this.duplicateTags.Add(hash);
                    }

                    foreach (string destFileName in fileList)
                    {
                        if (!destFileName.Equals(sourceFR.path))
                        {
                            FileReader destFR;
                            if (this.destFilesDict.TryGetValue(destFileName, out destFR)) {
                                if (sourceFR.tagDict.TryGetValue(profileType + " Author", out tag))
                                {
                                    author = this.convertHexToString(tag.data);
                                }

                                destHash = "";
                                if (profileType.Equals("Amp")) {
                                    destHash = destFR.ampHash;
                                }
                                if (profileType.Equals("Cab")) {
                                    destHash = destFR.cabHash;
                                }

                                this.tagGrid.Rows.Add(destFileName, "", profileType, author, destHash, "");
                                this.tagGrid.Rows[this.tagGrid.RowCount - 1].DefaultCellStyle = style;
                            }
                        }
                    }
                    return true;
                }
            }
            return false;
        }*/

        /*private string getAuthor(MidiTag tag, FileReader fr)
        {
            string author = "";
            if (tag.idString.StartsWith("Amp"))
            {
                MidiTag tag2;
                if (fr.tagDict.TryGetValue("Amp Author", out tag2))
                {
                    author = this.convertHexToString(tag2.data);
                }
            }
            else if (tag.idString.StartsWith("Cab"))
            {
                MidiTag tag2;
                if (fr.tagDict.TryGetValue("Cab Author", out tag2))
                {
                    author = this.convertHexToString(tag2.data);
                }
            }
            return author;
        }*/

        private string dumpTagsForFile(string filename)
        {
            string tagText = "";
            string profileText = "";
            FileReader fr = null;
            if (engine.sourceFilesDict.TryGetValue(filename, out fr)) ;
            else if (engine.destFilesDict.TryGetValue(filename, out fr)) ;
            if (fr != null)
            {
                foreach (MidiTag tag in fr.tags)
                {
                    if (tag.typeString.Equals("Tag"))
                    {
                        tagText += String.Format("{0,-2}{1,-20}{2,-25}\t{3,-40}", "* ", tag.typeString, tag.idString, this.convertHexToString(tag.data));
                        tagText += "\r\n";
                    }
                    else if (tag.typeString.Equals("Profile"))
                    {
                        profileText += String.Format("{0,-2}{1,-20}{2,-25}\t{3,-40}", "* ", tag.typeString, tag.idString, tag.hash);
                        profileText += "\r\n";
                    }
                }
            }
            return tagText + "\r\n" + profileText;
        }

        private string convertHexToString(byte[] hex)
        {
            return Encoding.ASCII.GetString(hex, 0, hex.Length - 1);
        }

        private void save_Click(object sender, EventArgs e)
        {
            int longestFilenameLen = 0;
            foreach (KeyValuePair<string, SourceFile> sourceFile in engine.sourceFiles)
            {
                if (sourceFile.Value.ampMatchFiles.Count > 0)
                {
                    if (sourceFile.Key.Length > longestFilenameLen)
                        longestFilenameLen = sourceFile.Key.Length;

                    foreach (KeyValuePair<string, FileReader> match in sourceFile.Value.ampMatchFiles)
                    {
                        if (match.Key.Length > longestFilenameLen)
                            longestFilenameLen = match.Key.Length;
                    }
                }

                if (sourceFile.Value.cabMatchFiles.Count > 0)
                {
                    if (sourceFile.Key.Length > longestFilenameLen)
                        longestFilenameLen = sourceFile.Key.Length;

                    foreach (KeyValuePair<string, FileReader> match in sourceFile.Value.cabMatchFiles)
                    {
                        if (match.Key.Length > longestFilenameLen)
                            longestFilenameLen = match.Key.Length;
                    }
                }

            }

            string output = "";
            string filename = "FILENAME";
            string type = "TYPE";
            string author = "AUTHOR";
            string hash = "HASH";
            string line = String.Format("{0,-" + (longestFilenameLen + 2) + "}{1,-6}{2,-30}{3,-40}\r\n", filename, type, author, hash);
            output += line;
            output += "----------------------------------------------------------------------------------------\r\n";

            foreach (KeyValuePair<string, SourceFile> sourceFile in engine.sourceFiles)
            {

                if (sourceFile.Value.ampMatchFiles.Count > 0)
                {
                    filename = sourceFile.Key;
                    type = "Amp";
                    author = sourceFile.Value.fr.getAmpAuthor();
                    hash = sourceFile.Value.fr.ampHash;
                    line = String.Format("{0,-" + (longestFilenameLen + 2) + "}{1,-6}{2,-30}{3,-40}\r\n", filename, type, author, hash);
                    output += line;

                    foreach (KeyValuePair<string, FileReader> match in sourceFile.Value.ampMatchFiles)
                    {
                        filename = match.Key;
                        type = "Amp";
                        author = match.Value.getAmpAuthor();
                        hash = match.Value.ampHash;
                        line = String.Format("{0,-" + (longestFilenameLen + 2) + "}{1,-6}{2,-30}{3,-40}\r\n", filename, type, author, hash);
                        output += line;
                    }
                    output += "----------------------------------------------------------------------------------------\r\n";
                }


                if (sourceFile.Value.cabMatchFiles.Count > 0)
                {
                    filename = sourceFile.Key;
                    type = "Cab";
                    author = sourceFile.Value.fr.getCabAuthor();
                    hash = sourceFile.Value.fr.cabHash;
                    line = String.Format("{0,-" + (longestFilenameLen + 2) + "}{1,-6}{2,-30}{3,-40}\r\n", filename, type, author, hash);
                    output += line;

                    foreach (KeyValuePair<string, FileReader> match in sourceFile.Value.cabMatchFiles)
                    {
                        filename = match.Key;
                        type = "Cab";
                        author = match.Value.getCabAuthor();
                        hash = match.Value.cabHash;
                        line = String.Format("{0,-" + (longestFilenameLen + 2) + "}{1,-6}{2,-30}{3,-40}\r\n", filename, type, author, hash);
                        output += line;
                    }
                    output += "----------------------------------------------------------------------------------------\r\n";
                }
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog.FilterIndex = 2;
            saveFileDialog.RestoreDirectory = true;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                System.IO.File.WriteAllText(@saveFileDialog.FileName, output);
            }
        }

        private void sourceFileGrid_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show(this.sourceFileGrid.CurrentCell.Value.ToString());  


            string filename = "";
            string type = "";
            string author = "";
            string hash = "";

            this.tagGrid.Rows.Clear();

            this.currentCellColor = this.sourceFileGrid.CurrentRow.DefaultCellStyle.BackColor;
            //MessageBox.Show(this.currentCellColor.ToString());

            string fullPath = this.sourceFileGrid.CurrentRow.Cells[0].Value.ToString();

            SourceFile sourceFile;
            if (engine.sourceFiles.TryGetValue(fullPath, out sourceFile))
            {
                if (this.viewAmpMatches.Checked)
                {
                    if (sourceFile.ampMatchFiles.Count > 0)
                    {
                        if (!this.hideSameAuthor.Checked || sourceFile.differentAmpAuthors)
                        {
                            filename = sourceFile.fr.path;
                            type = "Amp";
                            author = sourceFile.fr.getAmpAuthor();
                            hash = sourceFile.fr.ampHash;
                            this.addGridRow(filename, type, author, hash);
                            //this.tagGrid.Rows[this.tagGrid.RowCount - 1].DefaultCellStyle = style;
                            //this.addSourceFileRow(filename);
                            foreach (KeyValuePair<string, FileReader> match in sourceFile.ampMatchFiles)
                            {
                                if (!this.hideSameAuthor.Checked || !match.Value.getAmpAuthor().Equals(sourceFile.fr.getAmpAuthor()))
                                {
                                    filename = match.Key;
                                    type = "Amp";
                                    author = match.Value.getAmpAuthor();
                                    hash = match.Value.ampHash;
                                    this.addGridRow(filename, type, author, hash);
                                }
                            }
                        }
                        //this.switchColor();
                    }
                }

                if (this.viewCabMatches.Checked)
                {
                    if (sourceFile.cabMatchFiles.Count > 0)
                    {
                        if (!this.hideSameAuthor.Checked || sourceFile.differentCabAuthors)
                        {
                            filename = sourceFile.fr.path;
                            type = "Cab";
                            author = sourceFile.fr.getCabAuthor();
                            hash = sourceFile.fr.cabHash;
                            this.addGridRow(filename, type, author, hash);
                            //this.tagGrid.Rows[this.tagGrid.RowCount - 1].DefaultCellStyle = style;
                            //this.addSourceFileRow(filename);
                            foreach (KeyValuePair<string, FileReader> match in sourceFile.cabMatchFiles)
                            {
                                if (!this.hideSameAuthor.Checked || !match.Value.getCabAuthor().Equals(sourceFile.fr.getCabAuthor()))
                                {
                                    filename = match.Key;
                                    type = "Cab";
                                    author = match.Value.getCabAuthor();
                                    hash = match.Value.cabHash;
                                    this.addGridRow(filename, type, author, hash);
                                    //this.tagGrid.Rows[this.tagGrid.RowCount - 1].DefaultCellStyle = style;
                                }
                            }
                            //this.switchColor();
                        }
                    }
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Debug
            //this.sourceFolder.Text = "C:\\Users\\bob\\Dropbox\\kemper\\commercial raw\\sinmix";
            //this.destFolder.Text = "C:\\Users\\bob\\Dropbox\\kemper\\commercial raw";
            //this.sourceFolder.Text = "C:\\Users\\bob\\Dropbox\\kemper\\rig exchange";
            //this.destFolder.Text = "C:\\Users\\bob\\Dropbox\\kemper\\rig exchange";
            //this.sourceFolder.Text = "C:\\Users\\bob\\Dropbox\\kemper\\Utilities\\duplicateFinder\\testSrc";
            //this.destFolder.Text = "C:\\Users\\bob\\Dropbox\\kemper\\Utilities\\duplicateFinder\\testDest";
            //this.sourceFolder.Text = "C:\\Users\\bob\\Dropbox\\kemper\\Utilities\\duplicateFinder\\samefolder";
            //this.destFolder.Text = "C:\\Users\\bob\\Dropbox\\kemper\\Utilities\\duplicateFinder\\samefolder";
        }

        private void viewAmpMatches_CheckedChanged(object sender, EventArgs e)
        {
            this.populateGrid();
        }

        private void viewCabMatches_CheckedChanged(object sender, EventArgs e)
        {
            this.populateGrid();
        }

        private void hideSameAuthor_CheckedChanged(object sender, EventArgs e)
        {
            this.populateGrid();
        }
    }
}
